package com.tailyou.androidlearning2400.act

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import com.google.gson.Gson
import com.tailyou.androidlearning2400.act.ui.theme.AndroidLearning2400Theme
import com.tailyou.androidlearning2400.comp.BannerSlider
import com.tailyou.androidlearning2400.model.BannerItem
import com.tailyou.androidlearning2400.model.BannerResponse
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class BannerActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            val bannerList = remember { mutableStateListOf<BannerItem>() }
            AndroidLearning2400Theme {
                Column(modifier = Modifier.fillMaxSize()) {
                    // 轮播图组件
                    BannerSlider(
                        bannerList = bannerList, autoPlay = true, autoPlayDelay = 3000, // 3秒切换一次
                        bannerHeight = 220, // 轮播图高度220dp
                        onBannerClick = { url ->
                            // 轮播图点击事件：例如跳转详情页
                            println("点击了轮播图：$url")
                        })
                }
                loadBannerFromHttp(bannerList)
            }
        }
    }
}

/**
 * 从网络获取Banner数据
 */
private fun loadBannerFromHttp(bannerList: SnapshotStateList<BannerItem>) {
    val mainHandler = Handler(Looper.getMainLooper())
    val client by lazy { OkHttpClient() }
    val request = Request.Builder().url("https://www.wanandroid.com/banner/json")
        .addHeader("Cookie", "JSESSIONID=B4097E29EB37A60DEA91716290372E51").build()
    // 异步执行网络请求
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            // 请求失败（子线程）
            e.printStackTrace()
        }

        override fun onResponse(call: Call, response: Response) {
            // 请求成功（子线程）
            if (response.isSuccessful) {
                // 获取JSON字符串
                val jsonStr = response.body?.string() ?: ""
                // 核心：Gson解析JSON到数据类
                val bannerResponse = Gson().fromJson(jsonStr, BannerResponse::class.java)
                // 切换到主线程更新UI
                mainHandler.post {
                    bannerList.clear()
                    bannerList.addAll(bannerResponse.data)
                }
            }
            // 关闭response（避免内存泄漏）
            response.close()
        }
    })
}